// Mock authentication API for development testing

// 创建axios实例
import axios from 'axios';
import { refreshAuthInfo, clearAuthInfo } from '../utils/auth.js';

const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: true
});

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 这里可以添加请求前的处理，如添加token等
    const token = localStorage.getItem('userToken') || sessionStorage.getItem('userToken');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    console.error('请求拦截器错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data;
  },
  error => {
    console.error('响应拦截器错误:', error);
    return Promise.reject(error);
  }
);

// Mock用户数据
const mockUser = {
  id: '1',
  username: 'zhangsan123',
  name: '张老师',
  role: 1,
  roleName: '高级讲师',
  phone: '13800138000',
  email: 'zhangsan@example.com',
  avatar: '',
  isVerified: true,
  realName: '张三',
  verifiedAt: new Date().toISOString()
};

// Mock token
const mockToken = 'mock-jwt-token-for-development-testing';

export const authAPI = {
  // 模拟登录接口
  login: async (loginData) => {
    console.log('Mock login called with:', loginData);
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 接受任何用户名和密码进行登录（开发环境）
    console.log('Login successful (mock)', { username: loginData.username || 'zhangsan123' });
    
    // 构建模拟响应
    const response = {
      code: 200,
      message: '登录成功',
      data: {
        token: mockToken,
        role: mockUser.role,
        roleName: mockUser.roleName,
        name: mockUser.name,
        username: loginData.username || mockUser.username,
        teacher_id: 2025058,
        real_name: null,
        student_ids: ['2025060', '2025059', '2'],
        student_names: ['王林1', '王飞', '']
      }
    };
    
    // 保存所有认证信息到本地存储
    const rememberMe = loginData.rememberMe || false;
    refreshAuthInfo(response.data, rememberMe);
    
    return response;
  },
  
  // 模拟注册接口
  register: async (registerData) => {
    console.log('Mock register called with:', registerData);
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 800));
    
    // 构建模拟响应
    return {
      code: 200,
      message: '注册成功',
      data: {
        token: mockToken,
        role: registerData.role || 2, // 使用传入的role值，默认为2
        userId: 'new_' + Date.now()
      }
    };
  },
  
  // 模拟获取用户信息
  getUserInfo: async () => {
    console.log('Mock getUserInfo called');
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 300));
    
    // 构建模拟响应
    return {
      code: 200,
      message: '获取成功',
      data: mockUser
    };
  },
  
  // 模拟发送验证码
  sendVerificationCode: async (phone) => {
    console.log('Mock sendVerificationCode called with:', phone);
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 构建模拟响应
    return {
      code: 200,
      message: '验证码发送成功'
    };
  },
  
  // 模拟重置密码
  resetPassword: async (resetData) => {
    console.log('Mock resetPassword called with:', resetData);
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 600));
    
    // 构建模拟响应
    return {
      code: 200,
      message: '密码重置成功'
    };
  },
  
  // 登出功能 - 前端直接处理，不调用后端接口
  logout: () => {
    console.log('Mock logout called');
    
    // 清除所有认证信息
    clearAuthInfo();
    // 跳转到登录页面
    window.location.href = '/login';
  }
};